import json

from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet, GenericViewSet
from rest_framework import filters
import django_filters
from django_filters.rest_framework import FilterSet, DjangoFilterBackend
from rest_framework.decorators import action
from .models import *
from .Serializer import *
import requests


class UserInfoViewSet(ModelViewSet):
    queryset = UserInfo.objects.all()  # 必须指明该视图集在查询数据时使用的查询集
    serializer_class = UserInfoSerializer  # 必须指明该视图在进行序列化或反序列化时使用的序列化器


# 自定义过滤器
class ProjectFilter(FilterSet):
    name = django_filters.CharFilter(lookup_expr='icontains')  # icontains 模糊查询

    class Meta:
        models = Project
        fields = ['name']


class ProjectViewSet(ModelViewSet):
    queryset = Project.objects.all()  # 必须指明该视图集在查询数据时使用的查询集
    serializer_class = ProjectSerializer  # 必须指明该视图在进行序列化或反序列化时使用的序列化器
    # 过滤器
    filter_backends = [DjangoFilterBackend, filters.OrderingFilter]
    filterset_class = ProjectFilter
    filter_fields = ['name']


# #项目分组查询过滤器
# class ProjectGroupFilter(FilterSet):
#     project_id = ApiGroup.objects.all() #icontains 模糊查询
#     class Meta:
#         models = ApiGroup
#         fields = ['project_id']

class ApiGroupViewSet(ModelViewSet):
    queryset = ApiGroup.objects.all()  # 必须指明该视图集在查询数据时使用的查询集
    serializer_class = ApiGroupSerializer  # 必须指明该视图在进行序列化或反序列化时使用的序列化器
    # 过滤器
    # filter_backends = [DjangoFilterBackend, filters.OrderingFilter]
    # filterset_class = ProjectGroupFilter
    filter_fields = ['project_id']


class ApiInfoViewSet(ModelViewSet):
    queryset = ApiInfo.objects.all()  # 必须指明该视图集在查询数据时使用的查询集
    serializer_class = ApiInfoSerializer  # 必须指明该视图在进行序列化或反序列化时使用的序列化器
    filter_fields = ['project_id', 'group_id']


class ApiHeaderViewSet(ModelViewSet):
    queryset = ApiHeader.objects.all()  # 必须指明该视图集在查询数据时使用的查询集
    serializer_class = ApiHeaderSerializer  # 必须指明该视图在进行序列化或反序列化时使用的序列化器
    filter_fields = ['api_id']


class ApiQueryViewSet(ModelViewSet):
    queryset = ApiQuery.objects.all()  # 必须指明该视图集在查询数据时使用的查询集
    serializer_class = ApiQuerySerializer  # 必须指明该视图在进行序列化或反序列化时使用的序列化器
    filter_fields = ['api_id']


class ApiBodyViewSet(ModelViewSet):
    queryset = ApiBody.objects.all()  # 必须指明该视图集在查询数据时使用的查询集
    serializer_class = ApiBodySerializer  # 必须指明该视图在进行序列化或反序列化时使用的序列化器
    filter_fields = ['api_id']


'''发送请求 获取响应值 列表视图'''


class ApiResponseViewSet(ModelViewSet):
    queryset = ApiResponse.objects.all()  # 必须指明该视图集在查询数据时使用的查询集
    serializer_class = ApiResponseSerializer  # 必须指明该视图在进行序列化或反序列化时使用的序列化器
    filter_fields = ['api_id']

    # detail=True 需要传参  /api/response/pk/requests
    @action(methods=['post'], detail=False)
    def requests(self, request):
        api = request.data
        print(api)
        api_info = api['api_info']
        # 请求地址
        url = api_info['api_address']
        # http
        http_method = api_info['http_type']
        # 请求方式
        request_method = api_info['request_type']
        # 全局header
        # api_global_header = GlobalHeader.objects.filter(project_id=api_info.project_id).first()
        # 请求需要的参数
        headers = {}
        querys = {}
        body = {}
        print()
        if api.get('header'):
            for h in api['header']:
                headers[h['header_name']] = h['header_value']
        if api.get('query'):
            for q in api['query']:
                querys[q['query_name']] = q['query_value']
        body = api.get('body')
        response = ['请求未被执行']
        cookie = None
        print("headers: %s" % headers)
        print("querys: %s" % querys)
        print('body: %s' % body)
        if request_method == 'GET':
            response = requests.get(url=url, headers=headers, params=querys, cookies=cookie)
        elif request_method == 'POST':
            response = requests.post(url=url, headers=headers, params=querys, data=body, cookies=cookie)
        else:
            raise ValidationError('请求方式目前仅支持 GET，POST')

        # response = requests.get(url=url,params=params)
        # serializer = self.get_serializer(response.json)
        print(response)
        print(response.json)

        return Response({'url':response.url,
                         'status':response.status_code,
                         'encoding':response.encoding,
                         'headers':response.headers,
                         'cookie':response.cookies,
                         'response':response.text
                         })
